import json
from app01.models import Payment
from rest_framework.views import APIView
from app01.Baseview import BasedAPIView
from django import forms
from django.db.models import Q, Count, Sum
from datetime import datetime


class PayMentForm(forms.ModelForm):
    class Meta:
        model = Payment
        fields = ['name', 'price', 'end_time', 'remarks']


class PayMent_Api(BasedAPIView):
    def get_page_all(self, request):
        page = int(request.GET.get("page", 1))  # 获取get请求传递的参数 page
        pagesize = int(request.GET.get("pagesize", 10))
        uid = request.GET.get('id', None)
        name = request.GET.get("name", None)
        # start_time = request.GET.getlist("CreatedTime[]", [])
        query = Q()
        if name is not None:
            query &= Q(name__contains=name)

        # if len(start_time) == 1:
        #     parts = start_time[0].split('-')
        #     if len(parts) == 3:
        #         year, month, day = map(int, parts)
        #         query &= Q(start_time__year=year, start_time__month=month, start_time__day=day)
        datas = Payment.objects.filter(query).values()
        data_list = []
        for item in datas:
            now = datetime.now()
            item['remaining_days'] = (item['end_time'] - now).days
            item['end_time'] = item['end_time'].strftime("%Y-%m-%d")
            data_list.append(item)
        data_list = sorted(data_list, key=lambda x: x['remaining_days'])
        start_page = page * pagesize - pagesize
        end_page = page * pagesize
        paginated_data = data_list[start_page:end_page]
        total = Payment.objects.filter(query).count()
        total_price = Payment.objects.filter(query).aggregate(total_price=Sum('price'))['total_price']
        # print(total_price)
        data = {
            "total": total,
            "data": list(paginated_data),
            "total_price": total_price
        }
        return super().success(data=data)

    def add_info(self, request):
        form = PayMentForm(json.loads(request.body))
        if form.is_valid():
            form.save()
            return super().success(msg="添加成功", data=form.data)
        else:
            return super().error(msg=f"数据添加失败")

    def del_info(self, request):
        '''删除数据'''
        ids = request.GET.get("id", "")
        if ids == "":
            return super().error(msg="ID不能为空")
        ids = ids.split(",")   # 将字符串切割为列表
        ids_int = []
        for i in ids:
            if i == "":
                continue
            ids_int.append(int(i))  # 将id转换为数字类型 然后添加到新的列表中
        Obj = Payment.objects.filter(id__in=ids_int)  # id__in为 根据id字段 传入一个列表 批量查询需要删除的数据
        if not Obj.exists():    # 检测数据是否存在
            return super().error(msg="数据不存在")
        Obj.delete()    # 删除查询到的数据
        return super().success(msg="删除成功", data="")

    def edit_info(self, request):
        data = json.loads(request.body)
        uid = data.get('id')
        instance = Payment.objects.get(pk=uid)
        form = PayMentForm(data, instance=instance)
        if form.is_valid():
            form.save()
            return super().success(msg="修改成功", data=form.data)
        else:
            return super().error(msg="数据验证失败")